package com.spring.springboot.sys.jwt;

import cn.hutool.crypto.SecureUtil;
import com.spring.springboot.sys.core.constant.RedisConstants;
import com.spring.springboot.sys.core.model.UserInfo;
import com.spring.springboot.sys.util.RedisUtils;
import com.spring.springboot.sys.util.UserInfoUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 *
 * @author 宋义州
 * @date 2018/4/26
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String UPLOAD_CONTENT_TYPE = "multipart/form-data";

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain) throws ServletException, IOException, MultipartException {
        String authHeader = request.getHeader(RedisConstants.TOKEN_HEADER_NAME);
        if (StringUtils.isBlank(authHeader)) {
            String contentType = request.getContentType();
            if (contentType != null && contentType.contains(UPLOAD_CONTENT_TYPE)) {
                MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                // 将转化后的 request 放入过滤链中
                request = resolver.resolveMultipart(request);
            }
            authHeader = request.getParameter(RedisConstants.TOKEN_HEADER_NAME);
        }
        if (authHeader != null && authHeader.startsWith(RedisConstants.TOKEN_PREFIX)) {
            // The part after "Bearer "
            String authToken = authHeader.substring(RedisConstants.TOKEN_PREFIX.length());
            if (log.isDebugEnabled()) {
                log.debug("校验 authToken:{}", authToken);
            }
            // 用户名,租户ID
            String username;
            try {
                Claims claims = jwtTokenUtil.getClaimsFromToken(authToken);
                username = claims.getSubject();
            } catch (Exception e) {
                log.warn("token={}, 解析异常", authToken);
                chain.doFilter(request, response);
                return;
            }

            if (log.isDebugEnabled()) {
                log.debug("解析token获取 username:{}", username);
            }

            // 缓存当前用户信息
            UserInfo userInfo = new UserInfo();
            userInfo.setAccount(username);
            UserInfoUtils.setUserInfo(userInfo);

            // 校验authHeader
            String tokenMd5 = (String) redisUtils.get(String.format(RedisConstants.LOGIN_TOKEN_PREFIX, username));
            if (!SecureUtil.md5(authHeader).equals(tokenMd5)) {
                log.warn("当前用户未登录或者登录过期");
                chain.doFilter(request, response);
                return;
            }

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (userDetails == null) {
                    log.warn("获取当前用户信息失败，当前用户账户：{}", username);
                    chain.doFilter(request, response);
                    return;
                }
                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
